<script lang="ts" setup>
  import type { infoA } from "@@/apis/adv/type"
  import type { FormInstance, UploadFile } from "element-plus"
  import { adEdit,adSort,adInfo } from "@@/apis/adv"
  import { getproductList } from "@@/apis/good"
  import type { resGoodData } from "@@/apis/good/type"
  import { cloneDeep, forEach } from "lodash-es"
  import ggDialog from "./components/ggDialog/index.vue"
  import {  getGoodTranslate } from "@@/apis/good"
  import { useI18n } from 'vue-i18n';
const { locale, t } = useI18n();//登录国籍
import { inject } from 'vue'
const CL: any = inject("$CL");
  const router = useRouter()
  let route = useRoute();
  const ggDialogss = ref(false)
  let paymentObj = ref<object>({});
  const loading = ref<boolean>(false)
  const positonLists = ref([{
    name: '商城',
    name_ru:"Маркет",
    value: 0,
  },{
    name: '店铺',
    name_ru:"Магазин",
    value: 1,
  }])
  let params = route.params as {
    id?: string
  };
  const paramsId=ref(route.params.id)
// region 获取接口
  let sortList = ref<{name: string,value: number}[]>([])
  const getSort = async ()=> {
    // debugger
    let { data } = await adSort()
    let arr  = data.map((ele)=> {
      return {
        name: ele + '',
        value: ele,
      }
    })
    sortList.value = arr;
  }
  getSort();

  // 获取商品

  let goodList = ref<resGoodData[]>([])
  const getList = async (query:string)=> {
    let {data} = await getproductList({
      page: 1,
      limit: 50,
      ctime: '',
      keyword: query,
      status: "1",
      gid: ""
    })
    goodList.value = data.list;
    loadingSearch.value = false
  }

  const loadingSearch = ref(false);
  getList('');
  const remoteMethod = (query: string)=> {
      loadingSearch.value = true
      getList(query);
  }

// endregion
// region 增
  const DEFAULT_FORM_DATA: infoA = {
    id: undefined,
    name: "",
    tfwz: 0,
    pic: "",
    pic_ru: "",
    status: 1,
    admin_status:1,
    sort: '',
    url_id: '',
    is_cg: 0,
    locale: locale.value,
  }

  const formRef = ref<FormInstance | null>(null)
  const formData = ref<infoA>(cloneDeep(DEFAULT_FORM_DATA))
  const formRules = {
    name: [{ required: true, trigger: "blur", message: t('adv.输入广告标题')}],
    tfwz: [{ required: true, trigger: "change", message: t('adv.请选择投放位置') }],
    pic: [{ required: true, trigger: "blur", message:t('adv.请上传广告图片（中文）') }],
    pic_ru: [{ required: true, trigger: "blur", message: t('adv.请上传广告图片（俄文）')  }],
    url_id: [{ required: true, trigger: "change", message:t('adv.请选择商品链接')  }],
  }

  const confirmRelease = (state: number) => {
  console.log("state=========", state)
  let obj={}

     // formData.value.status=state
     formData.value.admin_status=1
     let list=['name']
     if(locale.value=='ru'){
      for (let key in formData.value) {
        list.forEach((item=>{
          if (key === item) {
            formData.value[key + '_ru'] = formData.value[key]; // 将值赋给新 key
            delete formData.value[key];        // 删除旧的 key
          }
        }))
      }
     }

     adEdit({
        info: {
          ...formData.value,
          status: state == 3 ? 3 :  formData.value.status
        }

      }).then((res:any) => {
        paramsId.value= res.data;
        if(state==3) return false
        if (formData.value.is_cg == 1) {
           ElMessage.success(t('common.保存草稿成功'))
          router.back();
        } else {
         ElMessage.success( t('common.操作成功'))
          ElMessageBox.alert(t('common.请等待平台确认，我们会尽快处理，谢谢提交申请成功'), {
            confirmButtonText:t('common.确认'),
            customClass: "new_box",
            callback: () => {
              router.back()
            },
          })
        }

      }).finally(() => {
        loading.value = false
      })
}
  function handleCreateOrUpdate(is_cg:number) {
    let picNum = countPicNum(formData.value);
      paymentObj.value = {
        picNum: picNum,
      };
    formRef.value?.validate((valid: boolean) => {
      if (!valid) {
         ElMessage.error(t('common.广告内容不能为空'))
        return
      }
      // debugger
      formData.value.is_cg = is_cg;
      //积分支付判断是添加广告掉取添加接口获取id
      if(paramsId.value=='0'&&is_cg!=1){
        confirmRelease(3)
      }
      if(is_cg==1){
      confirmRelease(1)
      }else{
        ggDialogss.value=true
      }

    })
  }

  // 计算图片数量
const countPicNum = (val: any) => {
  let nowNum = 0;
  let country = localStorage.getItem('country');
    if (val.pic) {
      nowNum = Math.round(nowNum + val.pic.split(",").length);
    }
    if (country === "ru") {
      if (val.pic_ru) {
      nowNum = Math.round(nowNum + val.pic_ru.split(",").length);
       }
    }
  return nowNum;
}

  const submitAddGood = async (val: any) => {
    loading.value = true
  switch (val.state) {
    case '0':
      //直接发布
    confirmRelease(1)
      break;
    case '1':
      //积分支付
      // formData.value.status=val.state
    let res = await getGoodTranslate({
        type:'3',
        yf_points: val.payPoints,
        fwids: val.fwids,
        fwnames: val.fwnames,
        ...formData.value
      })
      if (res.code === 1) {
        ElMessage.success( t('common.操作成功'))
        ElMessageBox.alert(t('common.请等待平台确认，我们会尽快处理，谢谢提交申请成功'), {
          confirmButtonText: t('common.确认'),
          customClass: "new_box",
          callback: () => {
            router.back();
          },
        })
      }
      break;

    default:
      break;
  }
 }

// 取消
const closeDialogVisible = () => {
  ggDialogss.value = false
  loading.value=false
}
const tfwz = (val) => {
  if(val==0){
    formData.value.sort=''
  }
}

  const getAction = ()=> {
    return import.meta.env.VITE_BASE_URL + "/?s=ApiImageupload/uploadImg";
  };
  let typeArr = [
    'image/jpg',
    'image/png',
    'image/jpeg',
  ]
  const beforeAvatarUploadFile = (rawFile: { type: string; size: number })=> {
    if (typeArr.indexOf(rawFile.type) < 0) {
      ElMessage.error(t('common.格式不正确,请上传jpg,jpeg,png格式'))
      return false
    } else if (rawFile.size / 1024 / 1024 > 3) {
      ElMessage.error(t('common.文件大小超过3M'))
      return false
    }
    return true;
  }

// 切换状态
const onSwitchChangeStatus = async ()=> {
  console.log(formData.value.status,'改变状态');


}
// 删除
const handleRemoveRu: UploadProps['onRemove'] = (uploadFile: any, uploadFiles: any) => {
  formData.value.pic_ru=''
}
const handleRemove: UploadProps['onRemove'] = (uploadFile: any, uploadFiles: any) => {
  formData.value.pic=''
}
  // 上传成功
  const handleAvatarSuccess = ( response:{url: string})=> {
    formData.value.pic = response.url;
  }
  const handleAvatarSuccessRu = ( response:{url: string})=> {
    formData.value.pic_ru = response.url;
  }

  const showViewer = ref(false)
  const concatPreviewList = ref<string[]>([])
  const  fileListPic = ref<{name: string,url: string}[]>([]);
  const  fileListPicRu = ref<{name: string,url: string}[]>([]);
  const handlePictureCardPreview = (uploadFile: UploadFile) => {
    concatPreviewList.value = [uploadFile.url!]
    showViewer.value = true
  }

  const onCancel = ()=> {
    router.back();
  }
// #endregion


// region 改



let query = route.query as unknown as {
  is_cg: number,
  admin_status: number
};

console.log("query=====", query)


const getAdvDetail = async ()=> {

  try {
    loading.value = true;
    let { data } = await adInfo({
      adid: params.id,
      is_cg: query.is_cg || 0,
    })

    if (Array.isArray(data) || !data) { // 是数组 返回值不存在 走创建
      loading.value = false;
      return;
    }
    formData.value = {
      id: params.id,
      name: data[CL('name')],
      tfwz: data.tfwz,
      pic: data.pic,
      pic_ru: data.pic_ru,
      status: data.status,
      sort: data.sort,
      url_id: data.url_id,
      is_cg: query.is_cg || 0,
    }
    fileListPic.value = [{
      name: data.name,
      url: data.pic,
    }]
    fileListPicRu.value = [{
      name: data.name,
      url: data.pic_ru,
    }]
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
}

// 创建
if(params.id != '0') getAdvDetail();
// 草稿
if(query.is_cg == 1) getAdvDetail();
// #endregion



</script>

<template>
  <div class="app-container" v-loading="loading">
    <el-form ref="formRef" :model="formData" :rules="formRules"  label-position="left">
      <el-form-item prop="name" :label="$t('adv.广告标题')">
        <div w-490px>
          <el-input v-model="formData.name" :placeholder="$t('adv.输入广告标题')" />
          <!-- :disabled="query.admin_status === 1" -->
        </div>
      </el-form-item>
      <el-form-item  prop="tfwz"  :label="$t('adv.投放位置')">
        <el-select v-model="formData.tfwz" :placeholder="$t('adv.请选择投放位置')" @change="tfwz" w-490px>
          <!-- :disabled="query.admin_status === 1" -->
          <el-option
            v-for="item in positonLists"
            :key="item.value"
            :label="item[CL('name')]"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <div class="position-relative">
        <el-form-item  prop="pic" :label="$t('adv.上传广告图片（中文）')">
          <el-upload
            :file-list="fileListPic"
            class="avatar-uploader"
            accept=".jpg, .jpeg, .png"
            :action="getAction()"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUploadFile"
            :on-remove="handleRemove"
            :multiple="false"
            list-type="picture-card"
            :limit="1"
            :data="{
              aid: 1,
            }"
            :on-preview="handlePictureCardPreview"
          >
          <!-- :disabled="query.admin_status === 1" -->
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <div class="color-#86909C font-size-12px font-400 position-absolute left-0 top-35px w-140px line-height-1.8em">{{$t('adv.支持jpg、png、jeg格式比例21：9大小单张限制到3m内')}}</div>
      </div>

      <div class="position-relative">
        <el-form-item  prop="pic_ru"  :label="$t('adv.上传广告图片（俄文）')">
          <el-upload
            :file-list="fileListPicRu"
            class="avatar-uploader"
            accept=".jpg, .jpeg, .png"
            :action="getAction()"
            :on-success="handleAvatarSuccessRu"
            :on-remove="handleRemoveRu"
            :before-upload="beforeAvatarUploadFile"
            :multiple="false"
            list-type="picture-card"
            :limit="1"
            :data="{
              aid: 1,
            }"
            :on-preview="handlePictureCardPreview"
          >
          <!-- :disabled="query.admin_status === 1" -->
          <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <div class="color-#86909C font-size-12px font-400 position-absolute left-0 top-35px w-140px line-height-1.8em">{{$t('adv.支持jpg、png、jeg格式比例21：9大小单张限制到3m内')}}</div>
      </div>

      <el-form-item  prop="status" :label="$t('adv.启用状态')"  required>
        <el-switch :active-value="1" :inactive-value="0" v-model="formData.status" :active-text="$t('adv.启用')"  :inactive-text="$t('adv.停用')" @change="onSwitchChangeStatus" style="--el-switch-on-color: #13ce66; "/>
      </el-form-item>
      <el-form-item  prop="sort"  :label="$t('adv.店铺内广告排序')">
        <el-select v-model="formData.sort" :placeholder="$t('adv.请选择')"  w-490px  filterable :disabled="formData.tfwz === 0 ? true : false">
          <el-option
            v-for="item in sortList"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item  prop="url_id"  :label="$t('adv.商品链接')">

        <el-select
          v-model="formData.url_id"
          :placeholder="$t('adv.请选择商品链接')"
          w-490px
          filterable
          remote
          :remote-method="remoteMethod"

          :loading="loadingSearch"
        >
        <!-- :disabled="query.admin_status === 1" -->
          <el-option
            v-for="item in goodList"
            :key="item.id"
            :label="item[CL('name')]"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>


    <div class="btns flex flex-justify-end mt-40px">
      <el-button @click="onCancel">{{$t('common.取消')}}</el-button>
      <el-button type="success" style="--el-button-bg-color: #13ce66; " @click="handleCreateOrUpdate(1)" v-if="query.is_cg ? true : false">{{$t('common.存为草稿')}}</el-button>
      <el-button type="primary" @click="handleCreateOrUpdate(0)">{{$t('common.提交')}}</el-button>

    </div>



    <!-- 图片预览器 -->
    <div class="demo-image__preview">
      <!-- element-plus内部组件 -->
      <el-image-viewer @close="() => { showViewer = false }" v-if="showViewer" :url-list="concatPreviewList" />
    </div>
     <!-- 新增编辑广告弹框 -->
    <ggDialog v-if="ggDialogss" :paymentObj="paymentObj" @confirmRelease="submitAddGood"
    @closeDialogVisible="closeDialogVisible"></ggDialog>
  </div>
</template>

<style lang="scss" scoped>
  .el-select {
    :deep(.el-select__wrapper) {
    }
  }

  .el-form {
    :deep(.el-form-item) {
      .el-form-item__label {
        color: #1D2129;
      }
    }
  }
</style>


